# =========================
# Tables 2–4 — Console output (stargazer)
# Left/Right only; English labels; totals; custom immigration labels
# =========================

library(tidyverse)
library(haven)
library(stringr)
library(stargazer)

# ---- Paths ----
base_dir <- "~/Dropbox/Issue voting Chile"

# ---- Helpers ----
pct1 <- function(x) sprintf("%.1f", 100 * x)  # render 0-100 with 1 decimal (no % sign)

# Build ideology from a12 (string like "1 Izquierda", "10 Derecha", "No sé/ Ninguna"...)
make_ideology_from_a12 <- function(df, a12_var = "a12") {
  a12_chr <- as.character(as_factor(df[[a12_var]]))
  a12_num <- suppressWarnings(as.numeric(str_match(a12_chr, "^(\\d+)")[,2]))
  df %>%
    mutate(
      ideology = case_when(
        a12_num %in% 1:4  ~ "Left",
        a12_num %in% 5:6  ~ "Center",
        a12_num %in% 7:10 ~ "Right",
        TRUE ~ NA_character_
      ),
      ideology = factor(ideology, levels = c("Left","Center","Right"))
    )
}

# Column-percentage helper (keeps only Left/Right, adds Total column)
col_pct_table_lr <- function(df, xvar) {
  df %>%
    filter(!is.na(ideology), ideology %in% c("Left","Right")) %>%
    count(!!sym(xvar), ideology, name = "n") %>%
    group_by(ideology) %>%
    mutate(p = n / sum(n)) %>%
    ungroup() %>%
    select(-n) %>%
    pivot_wider(names_from = ideology, values_from = p) %>%
    rowwise() %>%
    mutate(Total = mean(c(Left, Right), na.rm = TRUE)) %>%
    ungroup() %>%
    arrange(!!sym(xvar)) %>%
    rename(Item = !!sym(xvar)) %>%
    mutate(across(c(Left, Right, Total), pct1))
}

# =========================
# TABLE 2: Issue Agreement by Ideology (Left/Right + Total)
# =========================
wave2 <- read_dta(file.path(base_dir, "01_data/clean_data/wave2_conjoint.dta")) %>%
  make_ideology_from_a12("a12")

# English row labels
labels_a6_en <- c(
  a6a = "Democracy is the best form of government",
  a6b = "The state should own the main companies and industries",
  a6c = "The state should be primarily responsible for providing goods and services such as health and education",
  a6d = "Criminals have too many rights",
  a6e = "Immigration to Chile should be limited",
  a6f = "a6f (label pending)"
)
labels_a5_en <- c(
  a5a = "Same-sex marriage",
  a5b = "10% withdrawals from pension funds (AFP)",
  a5c = "Increase the minimum wage",
  a5d = "Reduce the size of the state",
  a5e = "Reinstate the death penalty",
  a5f = "Abortion on request up to 3 months",
  a5g = "Military intervention in La Araucanía"
)
items <- c(names(labels_a6_en), names(labels_a5_en))
agree_vals <- c("De acuerdo","Muy de acuerdo")

# Recode items to 1/0/NA
wave2 <- wave2 %>%
  mutate(
    across(all_of(items), ~ as.character(as_factor(.))),
    across(all_of(items), ~ case_when(
      .x %in% agree_vals ~ 1,
      .x %in% c("No sé","") ~ NA_real_,
      TRUE ~ 0
    ), .names = "{.col}_rec")
  )

# Build Table 2 with Total (overall mean)
mk_tab2_with_total <- function(df, which_items, labels_vec) {
  map_dfr(paste0(which_items, "_rec"), function(v) {
    tibble(
      Item  = labels_vec[str_remove(v, "_rec$")],
      Left  = mean(df[[v]][df$ideology == "Left"],  na.rm = TRUE),
      Right = mean(df[[v]][df$ideology == "Right"], na.rm = TRUE),
      Total = mean(df[[v]], na.rm = TRUE)
    )
  }) %>%
    mutate(across(c(Left, Right, Total), pct1)) %>%
    arrange(match(Item, labels_vec))
}

Table2_A <- mk_tab2_with_total(wave2, names(labels_a6_en), labels_a6_en)
Table2_B <- mk_tab2_with_total(wave2, names(labels_a5_en), labels_a5_en)

cat("\n============================\nTable 2: Issue Agreement by Ideology — Panel A (a6) [Left/Right + Total]\n")
stargazer(Table2_A, summary = FALSE, rownames = FALSE, type = "text")

cat("\n============================\nTable 2: Issue Agreement by Ideology — Panel B (a5) [Left/Right + Total]\n")
stargazer(Table2_B, summary = FALSE, rownames = FALSE, type = "text")

# =========================
# TABLE 3: Parents’ Vote in 1988, column % by ideology — keep ORIGINAL labels
# =========================
panel <- read_dta(file.path(base_dir, "01_data/clean_data/panel_long.dta"))

if ("a12" %in% names(panel)) {
  panel <- make_ideology_from_a12(panel, "a12")
} else if ("A12" %in% names(panel)) {
  panel <- make_ideology_from_a12(panel, "A12")
} else {
  panel <- panel %>%
    mutate(ideology = as_factor(ideology)) %>%
    mutate(ideology = fct_relevel(ideology, "Left","Center","Right"))
}

# Build tables (excludes "No sé/ No recuerdo/ No aplica"), Left/Right + Total
Table3_A <- panel %>%
  filter(wave == 1, !is.na(ideology), ideology %in% c("Left","Right"),
         A44_wave1 != "No sé/ No recuerdo/ No aplica") %>%
  col_pct_table_lr("A44_wave1")

Table3_B <- panel %>%
  filter(wave == 1, !is.na(ideology), ideology %in% c("Left","Right"),
         A43_wave1 != "No sé/ No recuerdo/ No aplica") %>%
  col_pct_table_lr("A43_wave1")

cat("\n============================\nTable 3 — Panel A: Mother’s Vote in 1988 (A44, wave=1) [Left/Right + Total]\n")
stargazer(Table3_A, summary = FALSE, rownames = FALSE, type = "text")

cat("\n============================\nTable 3 — Panel B: Father’s Vote in 1988 (A43, wave=1) [Left/Right + Total]\n")
stargazer(Table3_B, summary = FALSE, rownames = FALSE, type = "text")

# =========================
# TABLE 4: Attitudes Towards Immigration by Ideology (Left/Right + Total)
# =========================
wave2 <- wave2 %>% mutate(a56 = as_factor(a56))

lev <- levels(wave2$a56)
map_labels <- setNames(lev, lev)

map_labels[grepl("foment", lev, ignore.case = TRUE) | grepl("estimule", lev, ignore.case = TRUE)] <-
  "The government should encourage immigration"
map_labels[grepl("mantener", lev, ignore.case = TRUE) | grepl("actual", lev, ignore.case = TRUE) |
             grepl("pol[ií]tica", lev, ignore.case = TRUE)] <-
  "The government should keep the current policy"
map_labels[grepl("reduc", lev, ignore.case = TRUE) | grepl("cerr", lev, ignore.case = TRUE) |
             grepl("expuls", lev, ignore.case = TRUE) | grepl("ilegal", lev, ignore.case = TRUE)] <-
  "The government should reduce immigration by closing the borders or expelling illegal immigrants"

wave2 <- wave2 %>%
  mutate(a56_en = factor(map_chr(a56, ~ map_labels[.x]),
                         levels = c(
                           "The government should encourage immigration",
                           "The government should keep the current policy",
                           "The government should reduce immigration by closing the borders or expelling illegal immigrants"
                         )))

# Left/Right + Total
Table4 <- wave2 %>%
  filter(!is.na(ideology), ideology %in% c("Left","Right"), !is.na(a56_en)) %>%
  count(a56_en, ideology, name = "n") %>%
  group_by(ideology) %>%
  mutate(p = n / sum(n)) %>%
  ungroup() %>%
  select(-n) %>%
  pivot_wider(names_from = ideology, values_from = p) %>%
  rowwise() %>%
  mutate(Total = mean(c(Left, Right), na.rm = TRUE)) %>%
  ungroup() %>%
  arrange(a56_en) %>%
  rename(Item = a56_en) %>%
  mutate(across(c(Left, Right, Total), pct1))

# Final row labels (exact phrasing)
Table4$Item <- c(
  "The government should encourage immigration",
  "The government should keep the current policy",
  "The government should reduce immigration by closing the borders\nor expelling illegal immigrants"
)

cat("\n============================\nTable 4: Attitudes Towards Immigration by Ideology [Left/Right + Total]\n")
stargazer(Table4, summary = FALSE, rownames = FALSE, type = "text")

### Table E5: See 09_appendixF_tm

